package com.beinfo.contract.dao;

import java.sql.*;
import java.util.*;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.beinfo.contract.model.User;
import com.beinfo.contract.util.C3P0Util;


//import cn.edu.zucc.news.model.WebUser;
public class UserDao {
    private Connection conn = null;
    private Statement st = null;
    public UserDao() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager
                    .getConnection(
                    		"jdbc:mysql://localhost:3306/contract",
                            "t_user", "t_user");
            st = conn.createStatement();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
	public User findUserByUserNameAndPassword(String username, String password) throws SQLException {
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		return qr.query("select * from t_user where username=? and password=?",
				new BeanHandler<User>(User.class), username, password);
	}
	public synchronized User readUser(String userid) throws Exception{
        User result=null;
        try {
            ResultSet rs = st.executeQuery("select * from t_user where userid='"+userid+"'");
            if (rs.next()) {
                result=new User();
                result.setPassword(rs.getString("pwd"));
                result.setId(rs.getString("userid"));
                result.setusername(rs.getString("username"));
                result.setusertype(rs.getString("usertype"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("数据库查询错误");
        }
        
        return result;
        
    }

	public synchronized void addUser(User user) throws Exception{
        try {
            ResultSet rs = st.executeQuery("select * from t_user where userid='"+user.getUserid()+"'");
            if (rs.next()) {
                throw new Exception("登录号不能重复");
            }
            String sql="insert into t_user(userid,pwd,username,usertype) values('"+user.getUserid()+"','"
            +user.getPwd()+"','"+user.getUsername()+"','"+user.getUsertype()+"')";
            st.execute(sql);
        } catch (SQLException ex) {
            ex.printStackTrace();
            throw new Exception("数据库错误");
        }
        
    }


}
